package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ViewRelationMetadataEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SecurityValveAccount;
import com.ruoyi.system.domain.ViewRelationMetadata;
import com.ruoyi.system.entity.SysRemind;
import com.ruoyi.system.mapper.SecurityValveAccountMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.ViewConfigPushMesMapper;
import com.ruoyi.system.service.SecurityValveAccountService;
import com.ruoyi.system.service.SysRemindService;
import com.ruoyi.system.service.ViewRelationMetadataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 安全阀台账(SecurityValveAccount)表服务实现类
 *
 * @author makejava
 * @since 2022-12-14 12:00:12
 */
@Slf4j
@Service("securityValveAccountService")
public class SecurityValveAccountServiceImpl extends ViewRelationMetadataAbstract<List<SecurityValveAccount>> implements SecurityValveAccountService {
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ViewRelationMetadataService viewRelationMetadataService;

    @Resource
    private SecurityValveAccountMapper securityValveAccountDao;

    @Autowired
    private SysRemindService sysRemindService;
    @Resource
    private ViewConfigPushMesMapper viewConfigPushMesMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SecurityValveAccount queryById(Integer id) {
        return this.securityValveAccountDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param securityValveAccount 筛选条件
     * @param pageRequest          分页对象
     * @return 查询结果
     */
    @Override
    public Page<SecurityValveAccount> queryByPage(SecurityValveAccount securityValveAccount, PageRequest pageRequest) {
        long total = this.securityValveAccountDao.count(securityValveAccount);
        return new PageImpl<>(this.securityValveAccountDao.queryAllByLimit(securityValveAccount, pageRequest), pageRequest, total);
    }

    @Override
    public List<SecurityValveAccount> queryAll(SecurityValveAccount securityValveAccount) {
        List<SecurityValveAccount> securityValveAccounts = securityValveAccountDao.queryAll(securityValveAccount);
        return convert(securityValveAccounts);
    }

    /**
     * 新增数据
     *
     * @param securityValveAccount 实例对象
     * @return 实例对象
     */
    @Override
    public SecurityValveAccount insert(SecurityValveAccount securityValveAccount) {
        this.securityValveAccountDao.insert(securityValveAccount);
        return securityValveAccount;
    }

    /**
     * 修改数据
     *
     * @param securityValveAccount 实例对象
     * @return 实例对象
     */
    @Override
    public SecurityValveAccount update(SecurityValveAccount securityValveAccount) {
        this.securityValveAccountDao.update(securityValveAccount);
        return this.queryById(securityValveAccount.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.securityValveAccountDao.deleteById(id) > 0;
    }

    /**
     * 导入用户数据
     *
     * @param securityValveAccounts 用户数据列表
     * @param isUpdateSupport       是否更新支持，如果已存在，则进行更新数据
     * @param operName              操作用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importExcel(List<SecurityValveAccount> securityValveAccounts, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(securityValveAccounts) || securityValveAccounts.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        securityValveAccountDao.insertBatch(securityValveAccounts);
        return "成功";
    }

    @Override
    public List<SecurityValveAccount> convert(List<SecurityValveAccount> securityValveAccounts) {
        if (!CollectionUtils.isEmpty(securityValveAccounts)) {
            List<Integer> ids = securityValveAccounts.stream().map(SecurityValveAccount::getId).collect(Collectors.toList());
            Map<String, ViewRelationMetadata> relationMetadataMap = viewRelationMetadataService.queryMappingRelation(ViewRelationMetadataEnum.SECURITY_VALVE_ACCOUNT.name(), ids);
            log.info("relationMetadataMap 结果:{}", JSON.toJSON(relationMetadataMap));
            if (MapUtils.isNotEmpty(relationMetadataMap)) {
                for (SecurityValveAccount values : securityValveAccounts) {
                    String key = ViewRelationMetadataEnum.SECURITY_VALVE_ACCOUNT.name() + values.getId().toString();
                    ViewRelationMetadata viewRelationMetadata = relationMetadataMap.get(key);
                    log.info("viewRelationMetadata 结果:{}", JSON.toJSON(relationMetadataMap));
                    if (null != viewRelationMetadata) {
                        values.setMetadataFileName(viewRelationMetadata.getMetadataFileName());
                        values.setFileId(viewRelationMetadata.getFileId());
                        values.setFileName(viewRelationMetadata.getFileName());
                        values.setFileUrl(viewRelationMetadata.getFileUrl());
                    }
                }
            }
        }
        return securityValveAccounts;
    }

    @Scheduled(cron = "0 0 6 * * ?")
    public void checkPermitReportFile() {
        SecurityValveAccount securityValveAccount = new SecurityValveAccount();
        List<SecurityValveAccount> relateds = securityValveAccountDao.queryAll(securityValveAccount);
        if (CollectionUtils.isEmpty(relateds)) {
            return;
        }

        relateds.forEach(var -> {
            String remind = var.getNextCheckReportDate();
            Date date = new Date();

            Date parseDate = DateUtils.parseDate(remind);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(parseDate);
            // 把日期往后增加一天,整数  往后推,负数往前移动
            calendar.add(Calendar.DATE, -1);

            boolean after = date.after(calendar.getTime());
            if (after) {
                String stringBuffer =
                        "位号:" + var.getTagNo() +
                                "即将到期。";

                SysRole sysRole = new SysRole();
                sysRole.setRoleKey("qyzzts");
                List<SysUser> sysUsers = sysUserMapper.selectUserByRoleName(sysRole);
                if (CollectionUtils.isEmpty(sysUsers)) {
                    return;
                }

                for (SysUser sys : sysUsers) {
                    sysRemindService.insert(SysRemind.TYPE_PROMPT, stringBuffer, sys.getUserId().intValue());
                }

                List<String> collect = sysUsers.stream().map(SysUser::getWxUserId).collect(Collectors.toList());
                EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
                sendMessageRequest.setTouser(CollUtil.join(collect, "|"));
                sendMessageRequest.setMsgtype("text");
                sendMessageRequest.setAgentid(1000319);
                EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
                messageContent.setContent(stringBuffer);
                sendMessageRequest.setText(messageContent);
                enterpriseWXService.pushMessage(sendMessageRequest);

            }
        });
    }


}
